package com.yougou.ui.cart;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yougou.R;
import com.yougou.base.BaseActivity;
import com.yougou.data.model.Address;
import com.yougou.data.model.CartItem;
import com.yougou.data.model.Order;
import com.yougou.ui.address.AddressListActivity;
import com.yougou.utils.AddressManager;
import com.yougou.utils.CartManager;
import com.yougou.utils.OrderManager;
import com.yougou.utils.ToastUtils;
import com.yougou.utils.UserManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class CartCheckoutActivity extends BaseActivity {
    
    public static final String EXTRA_CART_ITEMS = "extra_cart_items";
    
    private TextView mTvUsername;
    private TextView mTvPhone;
    private TextView mTvAddress;
    private RecyclerView mRecyclerView;
    private TextView mTvTotalPrice;
    private Button mBtnSubmitOrder;
    
    private List<CartItem> mCartItems;
    private CartCheckoutAdapter mAdapter;
    private Address mCurrentAddress;
    
    private static final int REQUEST_SELECT_ADDRESS = 100;
    
    @Override
    protected void onCreate(android.os.Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart_checkout);
        initView();
        initData();
    }
    
    @Override
    protected void initView() {
        // 设置标题
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("确认订单");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        
        mTvUsername = findViewById(R.id.tv_username);
        mTvPhone = findViewById(R.id.tv_phone);
        mTvAddress = findViewById(R.id.tv_address);
        mRecyclerView = findViewById(R.id.rv_goods);
        mTvTotalPrice = findViewById(R.id.tv_total_price);
        mBtnSubmitOrder = findViewById(R.id.btn_submit_order);
        
        // 设置商品列表
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new CartCheckoutAdapter();
        mRecyclerView.setAdapter(mAdapter);
        
        // 点击地址区域，跳转到地址选择
        findViewById(R.id.card_address).setOnClickListener(v -> selectAddress());
        
        // 提交订单
        mBtnSubmitOrder.setOnClickListener(v -> submitOrder());
    }
    
    @Override
    protected void initData() {
        // 获取购物车商品
        ArrayList<CartItem> items = (ArrayList<CartItem>) getIntent().getSerializableExtra(EXTRA_CART_ITEMS);
        if (items == null || items.isEmpty()) {
            ToastUtils.show(this, "没有选中的商品");
            finish();
            return;
        }
        mCartItems = items;
        
        // 加载收货地址
        loadAddress();
        
        // 显示商品列表
        mAdapter.setData(mCartItems);
        
        // 计算总价
        double totalPrice = 0;
        for (CartItem item : mCartItems) {
            totalPrice += item.getSubtotal();
        }
        mTvTotalPrice.setText(String.format(Locale.CHINA, "¥%.2f", totalPrice));
    }
    
    
    private void loadAddress() {
        mCurrentAddress = AddressManager.getDefaultAddress();
        if (mCurrentAddress != null) {
            mTvUsername.setText(mCurrentAddress.getName());
            mTvPhone.setText(mCurrentAddress.getPhone());
            mTvAddress.setText(mCurrentAddress.getFullAddress());
            mBtnSubmitOrder.setEnabled(true);
        } else {
            // 没有地址
            mTvUsername.setText("请添加收货地址");
            mTvPhone.setText("点击此区域添加");
            mTvAddress.setText("暂无收货地址，请先添加");
            mBtnSubmitOrder.setEnabled(false);
        }
    }
    
    
    private void selectAddress() {
        android.content.Intent intent = new android.content.Intent(this, AddressListActivity.class);
        intent.putExtra(AddressListActivity.EXTRA_SELECT_MODE, true);
        startActivityForResult(intent, REQUEST_SELECT_ADDRESS);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_ADDRESS && resultCode == RESULT_OK && data != null) {
            Address address = (Address) data.getSerializableExtra(AddressListActivity.EXTRA_SELECTED_ADDRESS);
            if (address != null) {
                mCurrentAddress = address;
                mTvUsername.setText(address.getName());
                mTvPhone.setText(address.getPhone());
                mTvAddress.setText(address.getFullAddress());
                mBtnSubmitOrder.setEnabled(true);
            }
        }
    }
    
    
    private void submitOrder() {
        // 检查地址
        if (mCurrentAddress == null) {
            ToastUtils.show(this, "请先选择收货地址");
            selectAddress();
            return;
        }
        
        // 创建订单
        List<String> orderNumbers = new ArrayList<>();
        for (CartItem item : mCartItems) {
            Order order = OrderManager.createOrder(
                item.getGoods().getGoodsName(),
                item.getGoods().getGoodsPrice(),
                item.getQuantity(),
                item.getGoods().getGoodsPic(),
                mCurrentAddress.getName(),
                mCurrentAddress.getPhone(),
                mCurrentAddress.getFullAddress()
            );
            orderNumbers.add(order.getOrderNumber());
            
            // 从购物车删除
            CartManager.removeFromCart(item.getGoods().getGoodsId());
        }
        
        ToastUtils.show(this, "订单提交成功！共创建 " + orderNumbers.size() + " 个订单");
        
        // 返回
        finish();
    }
    
    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }
}

